class_name AdvancedMapGenerator
extends RefCounted

# 地图生成参数
const FLOORS_PER_ACT = 10
const NODES_PER_FLOOR = 3
const ELITE_FLOORS = [3, 7]
const BOSS_FLOOR = 10

# 节点类型权重
const NODE_WEIGHTS = {
	MapNode.NodeType.COMBAT: 50,
	MapNode.NodeType.REST: 12,
	MapNode.NodeType.SHOP: 8,
	MapNode.NodeType.EVENT: 8,
	MapNode.NodeType.TREASURE: 5,
	MapNode.NodeType.REMOVE_CARD: 5,
	MapNode.NodeType.UPGRADE_CARD: 5,
	MapNode.NodeType.HEAL_EVENT: 4,
	MapNode.NodeType.RANDOM_CARD: 3
}

var random_seed: int
var rng: RandomNumberGenerator

func _init(seed_value: int = 0):
	if seed_value == 0:
		seed_value = Time.get_unix_time_from_system()
	random_seed = seed_value
	rng = RandomNumberGenerator.new()
	rng.seed = random_seed

func generate_map() -> Array[Array]:
	var map: Array[Array] = []
	
	# 生成每一层
	for floor in range(1, FLOORS_PER_ACT + 1):
		var floor_nodes = _generate_floor(floor)
		map.append(floor_nodes)
	
	# 设置路径连接
	_setup_path_connections(map)
	
	return map

func _generate_floor(floor_num: int) -> Array[MapNode]:
	var nodes: Array[MapNode] = []
	
	# 根据新的布局规则生成节点（每层固定3个，用于菱形布局）
	if floor_num == 1:
		# 第一层：只能是战斗节点
		nodes.append(_create_node(MapNode.NodeType.COMBAT, floor_num, 0))
		nodes.append(_create_node(MapNode.NodeType.COMBAT, floor_num, 1))
		nodes.append(_create_node(MapNode.NodeType.COMBAT, floor_num, 2))
	elif floor_num in ELITE_FLOORS:
		# 精英楼层：1个精英节点，2个其他节点
		nodes.append(_create_elite_node(floor_num))
		nodes.append(_create_node(MapNode.NodeType.COMBAT, floor_num, 1))
		nodes.append(_create_node(MapNode.NodeType.EVENT, floor_num, 2))
	elif floor_num == BOSS_FLOOR:
		# Boss楼层：只有Boss节点
		nodes.append(_create_boss_node(floor_num))
		return nodes
	elif floor_num == BOSS_FLOOR - 1:
		# Boss前一层：休息节点（可以升级卡牌或回复血量）
		nodes.append(_create_node(MapNode.NodeType.REST, floor_num, 0))
		nodes.append(_create_node(MapNode.NodeType.UPGRADE_CARD, floor_num, 1))
		nodes.append(_create_node(MapNode.NodeType.HEAL_EVENT, floor_num, 2))
	elif floor_num <= 4:
		# 前4层：不能休息，只有战斗、事件、宝箱、商店
		var node_types = [MapNode.NodeType.COMBAT, MapNode.NodeType.EVENT, MapNode.NodeType.TREASURE, MapNode.NodeType.SHOP]
		for i in range(3):  # 每层3个节点
			var node_type = node_types[rng.randi() % node_types.size()]
			nodes.append(_create_node(node_type, floor_num, i))
	else:
		# 其他楼层：正常随机生成，包含休息
		for i in range(3):  # 每层3个节点
			var node_type = _choose_node_type(floor_num)
			nodes.append(_create_node(node_type, floor_num, i))
	
	# 设置节点位置
	_setup_node_positions(nodes)
	
	return nodes

func _choose_node_type(floor_num: int) -> MapNode.NodeType:
	# 根据楼层调整权重
	var weights = NODE_WEIGHTS.duplicate()
	
	# 前几层增加休息和商店概率
	if floor_num <= 3:
		weights[MapNode.NodeType.REST] += 10
		weights[MapNode.NodeType.SHOP] += 5
	
	# 后几层增加战斗概率
	if floor_num >= 10:
		weights[MapNode.NodeType.COMBAT] += 20
		weights[MapNode.NodeType.TREASURE] += 5
	
	# 随机选择节点类型
	var total_weight = 0
	for weight in weights.values():
		total_weight += weight
	
	var random_value = rng.randi_range(1, total_weight)
	var current_weight = 0
	
	for node_type in weights.keys():
		current_weight += weights[node_type]
		if random_value <= current_weight:
			return node_type
	
	return MapNode.NodeType.COMBAT

func _create_node(node_type: MapNode.NodeType, floor_num: int, index: int) -> MapNode:
	var node_id = "floor_" + str(floor_num) + "_node_" + str(index)
	return MapNode.new(node_id, node_type, floor_num, index, floor_num)

func _create_elite_node(floor_num: int) -> MapNode:
	var node_id = "floor_" + str(floor_num) + "_elite"
	return MapNode.new(node_id, MapNode.NodeType.ELITE, floor_num, 3, floor_num)

func _create_boss_node(floor_num: int) -> MapNode:
	var node_id = "floor_" + str(floor_num) + "_boss"
	return MapNode.new(node_id, MapNode.NodeType.BOSS, floor_num, 3, floor_num)

func _setup_node_positions(nodes: Array[MapNode]):
	# 设置节点的X位置：菱形交错布局，奇数层中间抬起，偶数层左右抬起
	# 我们只需设置同层内的 x_position（0,1,2）。实际像素位置在 MapView/MapConnection 里计算
	for i in range(nodes.size()):
		nodes[i].x_position = i

func _setup_path_connections(map: Array[Array]):
	# 简化路径：不建立具体连线，仅控制可达性（只能前进到下一层）
	# 第一层所有节点可访问
	if map.size() > 0:
		for node in map[0]:
			node.is_accessible = true
	
	# 清空所有连接（使用菱形自由选择下一层，不需要点到点连接）
	for floor_index in range(map.size() - 1):
		for node in map[floor_index]:
			node.next_floor_connections.clear()

func _setup_node_connections(map: Array[Array]):
	# 简化：不建立具体连接关系
	for floor_index in range(map.size() - 1):
		for current_node in map[floor_index]:
			current_node.next_floor_connections.clear()

func get_random_seed() -> int:
	return random_seed

func set_seed(new_seed: int):
	random_seed = new_seed
	rng.seed = new_seed
